package com.example.entity;

import com.example.utils.StringUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * TODO
 * 用户实体
 *
 * @Comment：最难的一次作业
 * @Date: 2023/11/18
 */
@Data

public class SysUser implements UserDetails {
    @ApiModelProperty(value = "主键")
    private Long id;

    @ApiModelProperty(value = "用户名")
    private String userName;

    @ApiModelProperty(value = "前端展示用户名")
    private String name;

    @ApiModelProperty(value = "用户昵称")
    private String nickName;

    @ApiModelProperty(value = "密码")
    private String password;

    @ApiModelProperty(value = "性别")
    private Integer sex;

    @ApiModelProperty(value = "头像")
    private String avatar;

    @ApiModelProperty(value = "地址")
    private String address;

    @ApiModelProperty(value = "小程序id")
    private String openId;

    @ApiModelProperty(value = "当前状态")
    private boolean status;

    @ApiModelProperty(value = "是否是管理员")
    private boolean admin;

    @ApiModelProperty(value = "电话号码")
    private String phoneNumber;

    @ApiModelProperty(value = "用户邮箱")
    private String email;

    @ApiModelProperty(value = "角色信息")
    private List<SysRole> roles;

    @ApiModelProperty(value = "用户对应的菜单列表")
    private List<SysMenu> menus;

    @ApiModelProperty(value = "用户对应的权限数据")
    private List<SysPermission> permissions;

    //权限数据集
    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> list = new ArrayList<>();
        // 通过stream流 过滤、迭代"角色信息list"，将非空内容添加到list中
        roles.stream().filter(role -> StringUtils.isNotEmpty(role.getCode()))
                .forEach(role -> list.add(new SimpleGrantedAuthority("ROLE" + role.getCode())));
        permissions.stream().filter(permission -> StringUtils.isNotEmpty(permission.getCode()))
                .forEach(permission -> list.add(new SimpleGrantedAuthority(permission.getCode())));

        return list;
    }

    //用户名
    @Override
    @JsonIgnore
    public String getUsername() {
        return userName;
    }

    //账号是否未过期
    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return false;
    }

    //账号是否未被锁定
    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return false;
    }

    //账号凭证(密码)是否未过期
    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return false;
    }

    //账号是否可用
    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return status;
    }
}
